package com.explorati.stack;

import java.util.Arrays;

public class Array<E> {

	private E[] data;
	private int size;

	// Java不支持new一个泛型的数组，得做一个转换 new Object[];然后强转
	public Array(int capacity) {
		data = (E[]) new Object[capacity];
		size = 0;
	}

	public Array() {
		this(10);
	}

	public int getSize() {
		return size;
	}

	public int getCapacity() {
		return data.length;
	}

	public boolean isEmpty() {
		return size == 0;
	}

	public void add(int index, E e) {
		if (size == data.length) {
			// throw new IllegalArgumentException("Add failed, array is full.");
			resize(2 * data.length);
		}
		if (index < 0 || index > size) {
			throw new IllegalArgumentException("Add failed, Require index >= 0 and index <= size");
		}
		for (int i = size; i > index; i--) {
			data[i] = data[i - 1];
		}
		data[index] = e;
		size++;
	}

	public void addLast(E e) {
		add(size, e);
	}

	public void addFirst(E e) {
		add(0, e);
	}

	public E get(int index) {
		if (index < 0 || index >= size) {
			throw new IllegalArgumentException("Get failed, Require index >= 0 && index < size");
		}
		return data[index];
	}

	public E getLast() {
		return get(size - 1);
	}

	public void set(int index, E e) {
		if (index < 0 || index >= size) {
			throw new IllegalArgumentException("Set failed, Require index >= 0 && index < size");
		}
		data[index] = e;
	}

	public boolean isContains(E e) {
		for (int i = 0; i < size; i++) {
			if (data[i].equals(e)) {
				return true;
			}
		}
		return false;
	}

	public E remove(int index) {
		if (index < 0 || index >= size) {
			throw new IllegalArgumentException("Require index >= 0 && index < size");
		}
		for (int i = index; i < size - 1; i++) {
			data[i] = data[i + 1];
		}
		size--;
		data[size] = null;// loitering objects != memory leak
		if (size == data.length / 4 && data.length / 2 != 0) {
			resize(data.length / 2);
		}
		return data[size];
	}

	public E removeLast() {
		return remove(size - 1);
	}

	public int find(E e) {
		for (int i = 0; i < size; i++) {
			if (data[i].equals(e)) {
				return i;
			}
		}
		return -1;
	}

	public void remove(E e) {
		int index = find(e);
		if (index != -1) {
			remove(index);
		}
	}

	@Override
	public String toString() {
		StringBuilder str = new StringBuilder();
		str.append(String.format("Array: size = %d, capacity = %d\n", size, data.length));
		str.append('[');
		for (int i = 0; i < size; i++) {
			str.append(data[i]);
			if (i != size - 1) {
				str.append(", ");
			}
		}
		str.append("]");
		return str.toString();
	}

	private void resize(int newCapacity) {
		E[] newData = (E[]) new Object[newCapacity];
		for (int i = 0; i < size; i++) {
			newData[i] = data[i];
		}
		data = newData;
	}

}
